<template>
  <div
    v-if="!initializing"
    ref="pageRef"
    class="vc-page"
    :style="visual.parseStyle(pageNode.currStyle)"
  >
    <component
      v-for="child in pageNode.children"
      :key="child.id"
      :is="'vc-' + child.type"
      :ref="el => setRefs(el, child)"
      :node="child"
      :inputParam="visual.getInputParam(child, props.inputParam)"
    />
  </div>
</template>

<script setup>
import { onMounted, ref, provide, getCurrentInstance, nextTick } from "vue";
import visual from "@/visual/js/visual";
import { useMobileStore } from '@/pinia/modules/mobile';
import { ElMessage } from "element-plus";
import EventHandler from "@/visual/js/event";

const props = defineProps({
  pageId: String,
  inputParam: Object
});

const initializing = ref(true);
const pageRef = ref();
const pageNode = ref({});
const mobileStore = useMobileStore();
const pageCompRefs = ref({});
const pageData = ref({});
const eventHandler = new EventHandler(null, getCurrentInstance(), pageNode.value);

provide('pageData', pageData);
provide('eventHandler', eventHandler);

const setRefs = (el, comp) => {
  if (el) {
    pageCompRefs.value[comp.id] = el;
  }
};

const getData = () => {
  return {
    ...pageData.value,
    inputParam: props.inputParam || {}
  };
};

onMounted(async() => {
  initializing.value = true;
  const page = await mobileStore.getPage(props.pageId);
  if (!page || !page.jsonText) {
    ElMessage.error('页面配置不正确！');
    return;
  }
  pageNode.value = JSON.parse(page.jsonText);
  if (!pageNode.value.currStyle
    && pageNode.value.styleList
    && pageNode.value.styleList.length > 0) {
    pageNode.value.currStyle = pageNode.value.styleList[0].style || {};
  }
  eventHandler.setNode(pageNode.value);
  eventHandler.initInputParam();

  const dataList = (await visual.loadData(
    pageNode.value.compData,
    eventHandler,
    getData(),
    pageNode.value)).data || [];
  const data = dataList.length > 0 ? dataList[0] : {};

  const globalParam = {};
  (pageNode.value.compData.fieldList || []).forEach(field => {
    globalParam[field.id] = data[field.name] || '';
  });
  Object.assign(globalParam, props.inputParam);
  pageData.value['inputParam'] = Object.assign({}, globalParam);
  eventHandler.setGlobalParam(globalParam);
  await nextTick(() => initializing.value = false);
});
</script>

<style>
#app {
  box-sizing: border-box;
}
</style>
<style scoped>
.mobile-page-container {
  box-sizing: border-box;
  height: 100%;
}
</style>